package com.xuan.yubi.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

public class FanoutConsumer {
    private static final String EXCHANGE_NAME = "fanout-exchange";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel1 = connection.createChannel();
        Channel channel2 = connection.createChannel();

        channel1.exchangeDeclare(EXCHANGE_NAME, "fanout");
        channel2.exchangeDeclare(EXCHANGE_NAME, "fanout");
        // 声明一个带有随机名称(自动分配)的队列
        String queueName1 = channel1.queueDeclare().getQueue();
        String queueName2 = channel2.queueDeclare().getQueue();
        // 将队列与交换机进行绑定，以订阅交换机发送的消息
        channel1.queueBind(queueName1, EXCHANGE_NAME, "");
        channel2.queueBind(queueName2, EXCHANGE_NAME, "");

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback deliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            System.out.println(" [x] Received '" + message + "'");
        };
        channel1.basicConsume(queueName1, true, deliverCallback, consumerTag -> {});
        channel2.basicConsume(queueName2, true, deliverCallback, consumerTag -> {});
    }
}